<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before>
          <span>共{{ page.total }}条记录 </span>
        </template>
        <template #after>
          <el-button size="small" type="danger" @click="exportData">普通excel导出</el-button>
          <el-button size="small" type="info">复杂表头excel导出</el-button>
          <el-button size="small" type="success" @click="$router.push('/import')">excel导入</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>


      <el-table
        :data="list"
        border
        style="width: 100%;margin-top: 20px">
        <el-table-column type="index" label="序号" width="100" align="center"/>
        <el-table-column prop="username" label="姓名" sortable/>
        <el-table-column prop="mobile" label="手机号" sortable/>
        <el-table-column prop="workNumber" label="工号" sortable/>
        <el-table-column prop="formOfEmployment" label="聘用形式" sortable :formatter="formatEmployment"/>
        <el-table-column prop="departmentName" label="部门" sortable/>
        <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          <template slot-scope="{ row }">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="状态" sortable>
          <template v-slot="{ row }">
            <el-switch :value="row.enableState === 1"/>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          width="300px">
          <template slot-scope="{row}">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="margin-top: 20px" justify="end">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="page.total"
          :page-size="page.pagesize"
          @current-change="handleCurrentChange">
        </el-pagination>
      </el-row>

      <AddEmployee :showDialog="showDialog"/>
      <assign-role ref="assignRole" :show-dialog.sync="showRoleDialog" :user-id="userId"/>

    </div>
  </div>
</template>

<script>
  import {getEmployeeList, delEmployee} from "@/api/employees";
  import EmployeeEnum from '@/api/constant/employees'
  import AddEmployee from "@/views/employees/components/add-employee";
  import {formatDate} from '@/filters'
  import AssignRole from "@/views/employees/components/assign-role";


  export default {
    components: {AssignRole, AddEmployee},
    data() {
      return {
        page: {
          total: 0,
          page: 1,
          size: 10
        },
        list: [],
        showDialog: false,
        showRoleDialog: false, // 分配角色弹层
        userId: null, // 记录当前点击的id
      }
    },
    created() {
      this.getEmployeeList()
    },
    comments: {
      AddEmployee
    },
    methods: {
      async getEmployeeList() {
        const {total, rows} = await getEmployeeList(this.page)
        this.page.total = total
        this.list = rows
      },
      handleCurrentChange(val) {
        this.page.page = val
        this.getEmployeeList()
      },
      //格式化聘用形式
      formatEmployment(row, column, cellValue, index) {

        const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
        return obj ? obj.value : '未知'
      },
      delEmployee(id) {
        this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await delEmployee(id)
          this.$message.success('删除成功!');
          this.getEmployeeList()
        }).catch(() => {

        });
      },
      exportData() {
        // 懒加载模块 => 只有当点击按钮的时候才去加载这个模块
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        import('@/vendor/Export2Excel').then(async excel => {
          // 获取所有的员工列表数据
          const {rows} = await getEmployeeList({page: 1, size: this.page.total})
          // excel导出的默认对象
          excel.export_json_to_excel({
            filename: '人力资源表',
            header: Object.keys(headers),
            data: this.formatJSON(headers, rows)
          })
        })
      },
      // 格式化json数据
      formatJSON(headers, rows) {
        return rows.map(item => {
          return Object.keys(headers).map(key => {
            let jsonKey = headers[key]
            if (jsonKey === 'timeOfEntry' || jsonKey === 'correctionTime') {
              return formatDate(item[jsonKey])
            } else if (jsonKey === 'formOfEmployment') {
              const obj = EmployeeEnum.hireType.find(o => o.id === item[jsonKey])
              return obj ? obj.value : '未知'
            }
            return item[jsonKey]
          })
        })
      },
      async assignRole(id){
        this.userId = id
        await this.$refs.assignRole.getUserDetailById(id)
        this.showRoleDialog = true
      }


    }

  }
</script>

<style scoped>

</style>
